package com.baofu.paycore.biz.paycore.handler.impl;

import com.baofu.clear.service.facade.enums.ClearStatusEnum;
import com.baofu.clear.service.facade.model.resp.NotifyDTO;
import com.baofu.paycore.biz.external.clear.WebClearChargeService;
import com.baofu.paycore.biz.external.clear.model.ClearFundResBO;
import com.baofu.paycore.biz.paycore.converter.BO2BOConverter;
import com.baofu.paycore.biz.external.clear.converter.ClearResultConverter;
import com.baofu.paycore.biz.model.WebPayBO;
import com.baofu.paycore.common.exception.PayCoreBizException;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import com.baofu.paycore.manager.model.RechargeBO;
import com.baofu.paycore.manager.model.RechargeFundBO;
import com.baofu.paycore.service.facade.enums.PayStatusEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;


/**
 * 充值订单处理
 *
 * <p/>
 *      1、异步充值
 * </p>
 * User: LZQ  Date: 2016/04/20 ProjectName: paycore Version: 5.0.0
 * User: kwl  Date: 2016/05/06 ProjectName: paycore Version: 5.0.0
 */
@Slf4j
@Service
public class WebRechargeHandler extends RechargeHandler{

    /**
     * 清分充值服务
     */
    @Autowired
    private WebClearChargeService webClearChargeService;

    /**
     * 页面跳转充值
     *
     * @param rechargeBO        请求对象
     * @return                  web跳转url
     */
    @Override
    public WebPayBO asyncProcess(RechargeBO rechargeBO){

        log.debug("开始处理web充值命令：{}", rechargeBO);
        checkBeforeProcess(rechargeBO);
        processOrders(rechargeBO);
        return BO2BOConverter.rechargeBO2WebPayBO(rechargeBO);
    }

    /**
     * 生成指令
     *
     * @param order 单据
     */
    @Override
    protected void processOrders(RechargeBO order) {
        //调用清分充值处理接口
        ClearFundResBO clearFundResBO = webClearChargeService.fundHandle(order);
        //返回结果对象转换成RechargeBO对象
        ClearResultConverter.result2RechargeBO(clearFundResBO, order);

        order.setStatus(clearFundResBO.getPayStat());
    }

    /**
     * web充值失败流程处理
     *
     * @param rechargeBO    充值单
     */
    private void failFundProcess(RechargeBO rechargeBO){
        rechargeBO.setStatus(PayStatusEnums.FAIL.getCode());
        for (RechargeFundBO rechargeFundBO : rechargeBO.getRechargeFundBO()){
            rechargeFundBO.setStatus(PayStatusEnums.FAIL.getCode());
        }
    }

    /**
     * 回调
     *
     * @return 回调处理响应
     */
    @Override
    public RechargeBO callBack(NotifyDTO callBackDTO) {
        //获取充值单信息
        RechargeBO rechargeBO = activeOrder(callBackDTO.getRequestBizNo());
        log.debug("充值订单加载结果, rechargeBO:{}", rechargeBO);
        rechargeBO.setTradeLogId(callBackDTO.getTradeLogId());
        rechargeBO.setEventNo(callBackDTO.getEventNo());

        //充值单成功，直接返回
        if (PayStatusEnums.SUCCESS.getCode().equals(rechargeBO.getStatus()) ||
                PayStatusEnums.FAIL.getCode().equals(rechargeBO.getStatus())) {
            return rechargeBO;
        }
        //判断清分单状态
        if (!dealBankFund(callBackDTO,rechargeBO)){
            reStore(rechargeBO);
            return rechargeBO;
        }
        //推进订单
        advance(rechargeBO);
        reStore(rechargeBO);
        return rechargeBO;
    }

    /**
     * 处理银行订单
     *
     * @param callBackDTO           回调参数
     * @param rechargeBO            充值订单
     * @return                      处理结果
     */
    private boolean dealBankFund(NotifyDTO callBackDTO,RechargeBO rechargeBO ){
        rechargeBO.setErrorCode(callBackDTO.getRespCode());
        rechargeBO.setErrorMsg(callBackDTO.getRespDesc());
        rechargeBO.setRealFlag(Objects.equals(callBackDTO.getStatus(), ClearStatusEnum.F.getCode()) ||
                Objects.equals(callBackDTO.getStatus(), ClearStatusEnum.S.getCode()));
        if(ClearStatusEnum.S.getCode().equals(callBackDTO.getStatus())){
            rechargeBO.setStatus(PayStatusEnums.SUCCESS.getCode());
            rechargeBO.getRechargeBankBO().setStatus(PayStatusEnums.SUCCESS.getCode());
            rechargeBO.getRechargeBankBO().setFundChannel(callBackDTO.getFundChannel());
            rechargeBO.getRechargeBankBO().setSubFundChannel(callBackDTO.getCounterNo());
            return true;
        }
        //清分状态转换支付状态
        if (ClearStatusEnum.I.getCode().equals(callBackDTO.getStatus())){
            rechargeBO.setStatus(PayStatusEnums.INIT.getCode());
            return false;
        }
        if(ClearStatusEnum.F.getCode().equals(callBackDTO.getStatus())) {
            rechargeBO.getRechargeBankBO().setStatus(PayStatusEnums.FAIL.getCode());
            failFundProcess(rechargeBO);
            return false;
        }
        log.error("未知的订单状态:{}",callBackDTO.getStatus());
        throw new PayCoreBizException(PayCoreErrorCode.BANK_REQUEST_ERROR,"未知的订单状态");
    }
}
